package servlet.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import dbutil.DBHelper;
import entity.User;
import net.sf.json.JSONObject;

public class EditUserServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Connection conn = null;
	JSONObject jsonObject = new JSONObject();
	boolean isSuccess = false;

	public EditUserServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		UserDao userDao = null;
		User user = null;
		
		
		try {
			conn = DBHelper.getConnection();
			conn.setAutoCommit(false);
			userDao = new UserDao();
			
			user = new User();
			user.setUserName(request.getParameter("userName"));
			user.setPassword(request.getParameter("password"));
			user.setCnname(request.getParameter("cnName"));
			user.setCategory(request.getParameter("category"));
			user.setDeptName(request.getParameter("deptName"));
			user.setEmail(request.getParameter("email"));
			// user.setStatus(request.getParameter("status"));
			user.setAdminName(request.getParameter("adminName"));
			
			isSuccess = userDao.editUser(user);
			judgeConn();
		} catch (SQLException e) {
			e.printStackTrace();
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "EditUserServlet dao");
		} finally {
			out.print(jsonObject.toString());
			out.close();
		}
	}
	
	// 返回值判断
	private void judgeConn() throws SQLException {
		if(isSuccess) {
			jsonObject.put("retCode", "1");
			conn.commit();
		} else {
			jsonObject.put("retCode", "0");
			jsonObject.put("desc", "EditUserServlet Exception");
			conn.rollback();
		}
		conn.setAutoCommit(true);
	}
	public void init() throws ServletException {
	}

}
